#!/usr/bin/env bash
set -euo pipefail

# Test for MISE_CEILING_PATHS functionality
# This tests that mise respects the ceiling paths configuration
# which prevents traversing up the directory tree beyond specified paths

# Create a test directory structure
TEST_ROOT=$(pwd)

# Setup directory structure
mkdir -p "$TEST_ROOT/parent/child/grandchild"

# Create config files at different levels using heredoc
mkdir -p "$TEST_ROOT/parent/mise-tasks"
cat <<EOF >"$TEST_ROOT/parent/mise-tasks/task-parent"
#!/usr/bin/env bash
echo parent
EOF
chmod +x "$TEST_ROOT/parent/mise-tasks/task-parent"

mkdir -p "$TEST_ROOT/parent/child/mise-tasks"
cat <<EOF >"$TEST_ROOT/parent/child/mise-tasks/task-child"
#!/usr/bin/env bash
echo child
EOF
chmod +x "$TEST_ROOT/parent/child/mise-tasks/task-child"

mkdir -p "$TEST_ROOT/parent/child/grandchild/mise-tasks"
cat <<EOF >"$TEST_ROOT/parent/child/grandchild/mise-tasks/task-grandchild"
#!/usr/bin/env bash
echo grandchild
EOF
chmod +x "$TEST_ROOT/parent/child/grandchild/mise-tasks/task-grandchild"

cd "$TEST_ROOT/parent/child/grandchild"

# Test 1: Normal behavior without ceiling paths
echo "Test 1: Without ceiling paths, should find all tasks up to parent"
assert_contains "mise tasks" "task-grandchild"
assert_contains "mise tasks" "task-child"
assert_contains "mise tasks" "task-parent"
echo "Test 1: Passed"

# Test 2: Set ceiling path to child directory
echo "Test 2: With ceiling path at child, should not find parent or child tasks"
export MISE_CEILING_PATHS="$TEST_ROOT/parent/child"
assert_contains "mise tasks" "task-grandchild"
assert_not_contains "mise tasks" "task-child"
assert_not_contains "mise tasks" "task-parent"
echo "Test 2: Passed"

# Test 3: Set ceiling path to grandchild directory
echo "Test 3: With ceiling path at grandchild, should not find any tasks"
export MISE_CEILING_PATHS="$TEST_ROOT/parent/child/grandchild"
assert_not_contains "mise tasks" "task-grandchild"
assert_not_contains "mise tasks" "task-child"
assert_not_contains "mise tasks" "task-parent"
echo "Test 3: Passed"

# Test 4: Multiple ceiling paths
echo "Test 4: With multiple ceiling paths"
export MISE_CEILING_PATHS="$TEST_ROOT/parent/child:$TEST_ROOT/parent"
assert_contains "mise tasks" "task-grandchild"
assert_not_contains "mise tasks" "task-child"
assert_not_contains "mise tasks" "task-parent"
echo "Test 4: Passed"

# Test 5: Ceiling path with non-existent directory
echo "Test 5: With non-existent ceiling path, should find all tasks"
export MISE_CEILING_PATHS="$TEST_ROOT/nonexistent"
assert_contains "mise tasks" "task-grandchild"
assert_contains "mise tasks" "task-child"
assert_contains "mise tasks" "task-parent"
echo "Test 5: Passed"

echo "All tests passed!"
